package com.itheima.train.manager.search.configuration;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

@Configuration
public class ElasticSearchConfiguration {

    @Autowired
    private Environment environment ;

    @Bean
    public RestHighLevelClient restHighLevelClient() {

        // 获取es集群的各个节点的配置信息
        String clusterInfos = environment.getProperty("es.cluster.nodes");
        String[] splitInfo = clusterInfos.split(",");
        HttpHost[] httpHosts = new HttpHost[splitInfo.length] ;
        for(int x = 0 ; x < splitInfo.length ; x++) {
            String[] split = splitInfo[x].split(":");
            HttpHost httpHost = new HttpHost(split[0] , Integer.parseInt(split[1])) ;
            httpHosts[x] = httpHost ;
        }

        // 返回一个RestHighLevelClient对象
        return new RestHighLevelClient(RestClient.builder(httpHosts)) ;

    }

}
